package com.amos.wx.config;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.amos.wx.constants.Const;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Amos
 * @ClassName DruidConfig
 * @Description Druid监控配置类
 * @Date 2018/11/22 21:10
 * @VERSION 1.0
 **/
@Configuration
public class DruidConfig {

    private static final String SPLIT_STR = ",";
    /**
     * 允许访问的IP地址
     */
    @Value("${druid.allow-ips}")
    private String allowIps;
    /**
     * 拒绝访问的ip地址
     */
    @Value("${druid.deny-ips}")
    private String denyIps;
    /**
     * 访问的用户名
     */
    @Value("${druid.login-username}")
    private String loginUserName;
    /**
     * 访问的密码
     */
    @Value("${druid.login-passwd}")
    private String loginPasswd;
    /**
     * 是否可以重置数据
     */
    @Value("${druid.reset-enable}")
    private String resetEnable;


    /**
     * 注册Druid Servlet访问的属性
     * @return
     */
    @Bean
    public ServletRegistrationBean startViewServlet() {
        // 创建Servlet注册实体
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(
                new StatViewServlet(), "/druid/*"
        );
        // 设置访问白名单
        if (StringUtils.isNoneBlank(allowIps)) {
            for (String ip : allowIps.split(SPLIT_STR)) {
                // 设置ip白名单
                servletRegistrationBean.addInitParameter("allow", ip);
            }
        }
        // 设置访问黑名单
        if (StringUtils.isNoneBlank(denyIps)) {
            for (String ip : denyIps.split(SPLIT_STR)) {
                // 设置ip白名单
                servletRegistrationBean.addInitParameter("deny", ip);
            }
        }

        // 设置控制台管理用户
        servletRegistrationBean.addInitParameter(Const.DruidConfig.DRUID_LOGIN_USER_NAME, loginUserName);
        servletRegistrationBean.addInitParameter(Const.DruidConfig.DRUID_LOGIN_USER_PASSWD, loginPasswd);
        // 是否可以重置数据
        servletRegistrationBean.addInitParameter(Const.DruidConfig.DRUID_RESET_ENABLE, resetEnable);
        return servletRegistrationBean;
    }

    /**
     * 创建过滤器
     * @return
     */
    @Bean
    public FilterRegistrationBean statFilter() {
        // 创建过滤器
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        // 设置过滤器过滤路径
        filterRegistrationBean.addUrlPatterns("/*");
        // 忽略过滤的形式
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }


}
